function TreeNode(val) {
  this.val = val;
  this.left = this.right = null;
}

function buildTree(preorder, inorder) {
  if (preorder.length === 0 || inorder.length === 0) {
      return null;
  }

  var rootVal = preorder[0];
  var root = new TreeNode(rootVal);

  var rootIndex = inorder.indexOf(rootVal);

  root.left = buildTree(
      preorder.slice(1, rootIndex + 1),
      inorder.slice(0, rootIndex)
  );

  root.right = buildTree(
      preorder.slice(rootIndex + 1),
      inorder.slice(rootIndex + 1)
  );

  return root;
}

// 示例输入
var preorder = [3, 9, 20, 15, 7];
var inorder = [9, 3, 15, 20, 7];

// 构建二叉树
var tree = buildTree(preorder, inorder);

// 输出构建好的二叉树
console.log(tree);